#include <modules\audio\fmod\fmod_music.h>

namespace DelGE
{
	namespace Modules
	{
		namespace Audio
		{
			FModMusic::FModMusic(string sFilepath, FMOD::System *pFModSystemHandle)
			{
				this->pFModSystemHandle = pFModSystemHandle;
				if (this->pFModSystemHandle->createSound(sFilepath.c_str(), FMOD_DEFAULT, NULL, &this->pSoundHandle) != FMOD_OK)
					throw("Could not load music file \"" + sFilepath + "\"");
				// To get a channel of the sound, we will play it paused.
				this->pFModSystemHandle->playSound(FMOD_CHANNEL_FREE, this->pSoundHandle, true, &this->pChannelHandle);

				this->ePlaybackMode = DelGEAudioPlaybackMode_PlayOnce;
				this->pSoundHandle->getLength(&this->uiLengthMS, FMOD_TIMEUNIT_MS);
			}

			FModMusic::~FModMusic()
			{
				this->pSoundHandle->release();
			}

			void FModMusic::Play()
			{
				this->pFModSystemHandle->playSound(FMOD_CHANNEL_FREE, this->pSoundHandle, false, &this->pChannelHandle);
				this->pChannelHandle->setVolume(this->fVolume);
				this->bIsPaused = false;
			}

			void FModMusic::SetPlaybackMode(DelGEAudioPlaybackMode ePlaybackMode)
			{
				this->ePlaybackMode = ePlaybackMode;

				switch(this->ePlaybackMode)
				{
				case DelGEAudioPlaybackMode_PlayOnce:
					this->pSoundHandle->setLoopCount(0);
					this->pSoundHandle->setMode(FMOD_LOOP_OFF);
					break;

				case DelGEAudioPlaybackMode_Loop:
					this->pSoundHandle->setLoopCount(-1);
					this->pSoundHandle->setMode(FMOD_LOOP_NORMAL);
					break;
				}
			}

			void FModMusic::Pause()
			{
				if (this->pChannelHandle != NULL)
				{
					this->pChannelHandle->setPaused(true);
					this->bIsPaused = true;
				}
			}

			void FModMusic::Resume()
			{
				if (this->pChannelHandle != NULL)
				{
					this->pChannelHandle->setPaused(false);
					this->bIsPaused = false;
				}
			}

			void FModMusic::SetVolume(float fVolume)
			{
				if (this->pChannelHandle != NULL)
				{
					if (fVolume < 0) fVolume = 0;
					if (fVolume > 1) fVolume = 1;

					this->pChannelHandle->setVolume(fVolume);
					this->fVolume = fVolume;
				}
			}

			float FModMusic::GetPosition()
			{
				if (this->pChannelHandle != NULL)
				{
					unsigned int uiPosition, uiSoundLength;
				
					this->pSoundHandle->getLength(&uiSoundLength, FMOD_TIMEUNIT_MS);
					this->pChannelHandle->getPosition(&uiPosition, FMOD_TIMEUNIT_MS);

					return (float)uiPosition / (float)this->uiLengthMS;
				}

				return 0;
			}

			bool FModMusic::IsPlaying()
			{
				if (this->pChannelHandle != NULL)
				{
					bool bIsPlaying;
					this->pChannelHandle->isPlaying(&bIsPlaying);
					return bIsPlaying;
				}

				return false;
			}
		}
	}
}
